<template>
  <div class="container">
    <el-page-header @back="goBack" content="临时回收码库"></el-page-header>
    <div class="e-m-t-45">
      <div class="flex">
        <div class="e-flex-1">
          <el-button type="primary" icon="el-icon-plus" plain @click="dialogVisible = true">打印</el-button>
        </div>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="关键词搜索">
            <el-input placeholder="请输入" v-model="key" prefix-icon="el-icon-search" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <el-divider></el-divider>
    <!-- <fieldset class="dz-preview-group">
            <legend>打印预览</legend>
            <div class="dz-preview" ref="preview-list"></div>
        </fieldset> -->
    <el-table :data="tableData" style="width: 100%" stripe>
      <el-table-column fixed type="index" width="50">
      </el-table-column>
      <el-table-column prop="qrnumber" label="编号">
      </el-table-column>
      <el-table-column prop="username" label="认领用户">
        <template slot-scope="scope">
          {{ scope.row.username?scope.row.username:'--' }}
        </template>
      </el-table-column>
      <el-table-column prop="scancodetime" label="认领时间">
        <template slot-scope="scope">
          {{ scope.row.scancodetime?scope.row.scancodetime:'--' }}
        </template>
      </el-table-column>
      <el-table-column prop="ordernumber" label="关联订单">
        <template slot-scope="scope">
          <div v-if="scope.row.ordernumber">
            <el-link v-if="scope.row.ordertype == 3" @click="goOrder('/order/brother/fitViews?id='+scope.row.orderid)"
              type="primary">{{ scope.row.ordernumber }}</el-link>
            <el-link v-else @click="goOrder('/order/user/Views?id='+scope.row.orderid)"
              type="primary">{{ scope.row.ordernumber }}</el-link>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="300">
        <template slot-scope="scope">
          <el-button @click="onDrawBarcode(scope.row.qrnumber)" type="text" size="small">打印</el-button>
          <el-button @click="onPrintJson(scope.row.qrnumber)" type="text" size="small">预览</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination background layout="sizes, total, prev, pager, next" :total="total" :page-sizes="[10, 50, 100, 200]"
        :page-size="pageSize" :current-page="page" @current-change="pageChange" @size-change="handleSizeChange">
      </el-pagination>
    </div>

    <!-- 批量打印处理 -->
    <el-dialog title="批量打印" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="printform" label-width="auto">
        <el-form-item label="打印张数">
          <el-input v-model="printform.num" type="number"></el-input>
        </el-form-item>
      </el-form>
      <!-- <div v-for="(item,index) in printTips" :key="index">
                {{ item }}
            </div> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" :disabled="printLoading">取消</el-button>
        <el-button type="primary" @click="createQrCode(printform.num)" :disabled="printLoading">打印并打印</el-button>
      </span>
    </el-dialog>

    <!-- 预览一维码 -->
    <el-dialog title="预览一维码" :visible.sync="dialogVisible1" width="500px">
      <div class="u-p-30">
        <div class="dz-preview" style="text-align: center;" ref="preview-list"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  // 打印组件引入
  import {
    DTPWeb,
    LPA_JobNames,
    LPA_PrintActions
  } from "dtpweb";

  export default {
    layout: 'admin',
    head() {
      return {
        title: '临时回收码库-' + this.websetting.name
      }
    },
    data() {
      return {
        tableData: [],
        key: '',
        page: 1,
        pageSize: 10,
        total: 0,
        printers: [{
          name: "未检测到打印机",
          value: {}
        }],
        // 批量打印处理
        printform: {
          num: 1
        },
        printLoading: false,
        dialogVisible: false,
        api: undefined,
        currPrinter: {
          name: ""
        },
        currJobName: LPA_JobNames.Preview,
        // 预览一维码
        dialogVisible1: false
      }
    },
    mounted() {
      this.getList()
      DTPWeb.getInstance().checkPlugin((api) => {
        this.api = api;
        if (api) {
          this.updatePrinterList();
        } else {
          this.printers[0].name = "未检测到打印插件";
        }
      });
    },
    methods: {
      goBack() {
        this.$router.go(-1)
      },
      getList() {
        this.$axios.post('/Admin/User/Order/QrCodeList', {
          "PageIndex": this.page,
          "PageSize": this.pageSize,
          "Key": this.key,
        }).then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
        })
      },
      pageChange(e) { // 页码切换事件
        this.page = e;
        this.getList()
      },
      handleSizeChange(val) {
        this.page = 1;
        this.pageSize = val;
        this.getList()
      },
      goOrder(path) {
        this.$router.push({
          path: path
        })
      },
      // 创建回收码
      async createQrCode(total) {
        this.$axios.get('Admin/User/Order/CreateQrCode?total=' + total).then(async (res) => {
          this.$message.success(res.msg);

          this.printLoading = true
          await this.onOopenPrinter()

          let length = res.length
          let num = -1
          // 一秒打印一次
          let timer = setInterval(async () => {
            num++
            if (num > length - 1) {
              clearInterval(timer);
              this.printLoading = false
              return
            } else {
              await this.onDrawBarcode(res[num].qrcode)
            }
          }, 1000)

          this.dialogVisible = false;

          this.getList()
        })
      },
      /**
       * 更新打印机列表。
       */
      updatePrinterList() {
        if (!this.api) return;
        //
        this.api.getPrinters().then((values) => {
          // 清空旧打印机列表
          this.printers.splice(0);
          //
          if (values?.length > 0) {
            for (const item of values) {
              const title = item.type === 1 ? item.name : `${item.name}@${item.ip}`;
              this.printers.push({
                name: title,
                value: item,
              });
            }
            //
            this.currPrinter = values[0];
            // 更新打印参数
            // this.updatePrintParams();
          } else {
            this.printers.push({
              name: "未检测到打印机",
              value: ""
            });
          }
        });
      },
      /**
       * 打开打印机测试
       */
      async onOopenPrinter() {
        const printer = this.printers[0].value;
        const value = await this.api?.openPrinter(printer);
        // alert(value ? "打印机打开成功!" : "打印机打开失败");
        if (!value) {
          alert("打印机打开失败,请确保已连接打印机或安装了驱动")
        }
      },
      /**
       * 打印一维码
       */
      async onDrawBarcode(name) {
        console.log(name)
        const width = 45;
        const height = 30;
        const text = name;
        const margin = 5;

        await this.api.startJob({
          width,
          height
        });
        await this.api.draw1DBarcode({
          text,
          x: margin + 2,
          y: margin,
          width: width - margin * 2,
          height: height - margin * 2,
          textHeight: 5,
          horizontalAlignment: 1,
        });
        await this.api.commitJob();
      },
      previewPages(pages) {
        if (pages && pages.length > 0) {
          for (const page of pages) {
            this.addPreview(page);
          }
        }
      },
      addPreview(data) {
        if (!data) return;
        const previewGroup = this.$refs["preview-list"];
        const img = document.createElement("img");
        img.src = data;
        previewGroup.appendChild(img);
        // 换行
        previewGroup.appendChild(document.createElement("br"));
      },
      getJobAction() {
        if (this.currJobName === LPA_JobNames.Preview) return LPA_PrintActions.PrevBase64;
        else if (this.currJobName === LPA_JobNames.Transparent) return LPA_PrintActions.TransBase64;
        else return LPA_PrintActions.Print;
      },
      /**
       * 打印JSON格式绘制任务。
       */
      async onPrintJson(name) {
        this.dialogVisible1 = true
        setTimeout(async () => {
          this.$refs["preview-list"].innerHTML = "";

          // const printerName = this.currPrinter ? this.currPrinter.name : undefined;
          // if (this.isPrintJob() && !printerName) return;
          //
          const printAction = this.getJobAction();
          const labelWidth = 40;
          const labelHeight = 30;
          // var url = 'http://www.detonger.com/img/QRCode_OfficialAccounts.png';
          // var text1 = '上海道臻信息技术有限公司';
          // var text2 = '1234567';
          //
          const results = await this.api.print({
            action: printAction,
            printerInfo: {
              printerName: this.currPrinter.name,
            },
            jobInfo: {
              jobWidth: labelWidth,
              jobHeight: labelHeight,
              orientation: 0
            },
            jobPages: [
              // 第一张标签，外边框里面套个二维码
              [{
                  type: "rectangle",
                  width: labelWidth,
                  height: labelHeight,
                  lineWidth: 0.4
                },
                // { type: 'roundRectangle', width: labelWidth, height: labelHeight, lineWidth: 0.4, cornerWidth: 2 },
                // { type: 'text', text: text1, width: labelWidth, height: labelHeight, fontHeight: 4 },
                {
                  type: "barcode",
                  text: name,
                  x: 5,
                  y: 5,
                  width: 30,
                  height: 20,
                  textHeight: 4,
                  textAlignment: 3,
                },
                // { type: 'qrcode', text: text1, x: 10, y: 5, width: 20, eccLevel: 1 },
                // { type: 'pdf417', text: text2, x: 5, y: 5, width: 30, height: 20 },
                // // 绘制图片url
                // { type: 'image', imageFile: url, x: 10, y: 5, width: 20, height: 20 },
                // // 绘制BASE64字符串
                // { type: 'image', imageFile: imgSrc, x: 10, y: 5, width: 20, height: 20 },
                // { type: 'line', x1: 0, y1: 5, x2: labelWidth, y2: 5, lineWidth: 0.4 },
                // { type: 'dashLine', x1: 0, y1: 10, x2: labelWidth, y2: 10, lineWidth: 0.4, dashLen: '1,0.5' },
              ],
            ],
          });
          // 显示预览效果
          if (printAction !== 0x1000 && results) {
            await this.previewPages(results.previewData);
          }
        }, 100);
      },
    }
  }
</script>
